package yi.master.coretest.message.process.util.ysb;

import cn.hutool.core.date.DateUtil;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Date;

/**
 * @author 502341194@gmail.com
 * @ClassName MDFive
 * @date 2020/1/15 9:24
 * @Description TODO
 * @Version 1.0
 **/
public class MDFive {

    private static final String[] hexDigits = {"0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"};


    public static String getMD5(String sourceStr) {
        String resultStr = "";
        try {
            byte[] temp = sourceStr.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(temp);

            byte[] b = md5.digest();
            for (int i = 0; i < b.length; i++) {
                char[] digit = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

                char[] ob = new char[2];
                ob[0] = digit[(b[i] >>> 4 & 0xF)];
                ob[1] = digit[(b[i] & 0xF)];
                resultStr = resultStr + new String(ob);
            }
            return resultStr;
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    private static String byteArrayToHexString(byte[] b) {
        StringBuffer resultSb = new StringBuffer();
        for (int i = 0; i < b.length; i++) {
            resultSb.append(byteToHexString(b[i]));
        }
        return resultSb.toString();
    }

    private static String byteToHexString(byte b) {
        int n = b;
        if (n < 0)
            n += 256;
        int d1 = n / 16;
        int d2 = n % 16;
        return hexDigits[d1] + hexDigits[d2];
    }

    public static String MD5Encode(String origin, String charsetname) {
        String resultString = null;
        try {
            resultString = new String(origin);
            MessageDigest md = MessageDigest.getInstance("MD5");
            if ((charsetname == null) || ("".equals(charsetname))) {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes()));
            } else {
                resultString = byteArrayToHexString(md.digest(resultString.getBytes(charsetname)));
            }
        } catch (Exception exception) {
        }
        return resultString;
    }

    public static void main(String args[]) throws Exception {
      //  String signStr = "hnysb001hnds@2020#@@114.215.139.111hnlkysbkey";
        System.out.println(DateUtil.format(new Date() ,"yyyyMMdd"));
        String signStr = "hnysb001hnds@2020#@@"+ DateUtil.format(new Date() ,"yyyyMMdd");
        System.out.println(getMD5(signStr));
        // 0C801C285DB007E8A27D7D9BA09EFE99
    }
}
